<?php
namespace Common\Controller;
use Think\Controller;
class CommonController extends Controller
{
    protected function _initialize()
    {
	    header("Content-Type: text/html;charset=utf-8");
        $this->checkLoginSession();
        $this->checkAdminSession();

        $userid=session('userid');
        $info=M('account')->where(array('id' => $userid))->find();

        session('userid',$info['id']);
        session('username',$info['account']);
        session('name',$info['name']);
        session('phone',$info['phone']);
        session('email',$info['email']);
        session('cart_id',$info['cart_id']);
        session('yhkh',$info['bank_num']);
        session('khyh',$info['bank_name']);
        session('khxm',$info['bank_username']);
        session('zhhxx',$info['bank_zhi']);
        session('province',$info['province']);
        session('status',$info['status']);//0  未开通，１已开通　２休眠　３冻结　
        session('price',$info['investmoney']);//投资额度
        session('txprice',$info['cashmoney']);//提现钱包
        session('yearprice',$info['yearmoney']);//半年钱包
        session('halfprice',$info['halfmoney']);//季度钱包
        session('ztprice',$info['zhitui']);//直推提现钱包
        session('logintime',time());//登录时间
        session('zctime',$info['zctime']);//注册时间
        if($info['level']==0){
            session('level','免费会员');
            session('bg','bg-1');
        }
        if($info['level']==1){
            session('level','正式会员');
            session('bg','bg-2');
        }
        if($info['level']==2){
            session('level','普通代理');
            session('bg','bg-3');
        }
        if($info['level']==3){
            session('level','一级代理');
            session('bg','bg-4');
        }
        if($info['level']==4){
            session('level','二级代理');
            session('bg','bg-5');
        }
        if($info['level']==5){
            session('level','终极代理');
            session('bg','bg-6');
        }
        // if($info['level']==6){
        //     session('level','终极代理');
        // }

        $yhfmessage = M('message')->where(array('userid' => $userid,'status' => 1))->count();
        $this->assign('yhfmessage',$yhfmessage);


        $setting=M('setting')->where('id=1')->find();
        $this->assign('setting',$setting);

        $news=M('news')->order('id desc')->limit(1)->find();
        $this->assign('news',$news);


        $last=M('reward')->where(array('typemoney' => 1))->order('times_c desc')->limit(1)->find();
        if(date('Y-m-d', $last['times_c'])!=date('Y-m-d', time())) {
            // echo date('Y-m-d', $last['createtime']);
            // $quanbu=M('account')->where('status=1 and investmoney>0')->select();
            $quanbu=M('account')->where('status=1')->select();
            // dump($quanbu);die;

            for($j=0;$j<count($quanbu);$j++){
                $this->backcash($quanbu[$j]['id']);//每天返现收益(日分红)
                $this->jiangjin($quanbu[$j]['id']);//管理奖
            }

        }


        $z_jj=M('reward')->where(array('uid' => $userid))->sum('money');//总奖金
        $zhijj=M('reward')->where(array('uid' => $userid,'typemoney' => 2))->sum('money');//直推奖金
        // $user['zhijj']=$zhijj;//直推奖金
        $z_fh=$z_jj-$zhijj+0;//总分红

        $BeginDate=date('Y-m-01 00:00:00', strtotime(date("Y-m-d")));//当月的第一天
        $EndDate=date('Y-m-d 23:59:59', strtotime("$BeginDate +1 month -1 day"));//当月的最后一天
        // echo $BeginDate.'<br>';
        // echo $EndDate;
        $day1=strtotime($BeginDate);
        $day2=strtotime($EndDate);
        $map['times_c'] = array(array('egt',$day1),array('elt',$day2));
        $map['uid'] = $userid;
        $map['typemoney'] = 1;
        $jj1=M('reward')->where($map)->sum('money');

        $map['typemoney'] = 3;
        $jj3=M('reward')->where($map)->sum('money');

        $yue_fh=$jj1+$jj3+0;//本月分红

        $ktx_fh=($z_fh-$yue_fh)*0.5;//直接提现钱包可提现分红

        session('ktx_fh',$ktx_fh);//直接提现钱包可提现分红

        $banntime=time()-6*30*24*60*60;
        $today=time();
        $map2['times_c'] = array(array('egt',$banntime),array('elt',$today));
        $map2['uid'] = $userid;
        $map2['typemoney'] = 1;
        $bann_jj1=M('reward')->where($map2)->sum('money');

        $map2['typemoney'] = 3;
        $bann_jj3=M('reward')->where($map2)->sum('money');

        $yue6_fh=$bann_jj1+$bann_jj3+0;//今天及以前6个月的分红（180天）

        $ktx_year=($z_fh-$yue6_fh)*0.3;//半年分红钱包可提现分红

        session('ktx_year',$ktx_year);//半年分红钱包可提现分红


        $adminbank=M('bank')->where(array('userid' => 0))->select();
        $this->assign('adminbank', $adminbank);
        
        

    }
	

	public function checkLoginSession() 
    {  
	   
		if(empty($_SESSION['username'])||empty($_SESSION['userid']))
		{
            unset($_SESSION['username']);  
            
			echo "<script>alert('用户未登录，请先登录！');location.href='/'</script>";
			die();
        }
    }
    public function checkAdminSession() {

        //设置超时为1小时
        $nowtime = time();
        $s_time = $_SESSION['logintime'];
        if (($nowtime - $s_time) > 3600) {
            unset($_SESSION['logintime']);
            
            echo "<script>alert('用户登录超时，请重新登录！');location.href='/'</script>";
            die();
        } else {
            $_SESSION['logintime'] = $nowtime;
        }
    }


    /**
     * 密码加密
     */
    function md5pw($passwd)
    {
        $ph = new \Think\PasswordHash();
        return $ph->HashPassword($passwd);

    }

    /**
     * 检测密码是否正确
     * @param $getPwd
     * @param $dataPasswd
     */
    function _checkPwd($getPwd,$dataPasswd)
    {
        $ph = new \Think\PasswordHash();
        if($ph->CheckPassword($getPwd,$dataPasswd))
        {
            return true;
        }
        else
        {
            return false;
        }
    }


    // //获取公告
    // public function get_news()
    // {
    //     $D=M('news');
    //     $data=$D->order('id desc')->select();
    //     $news_number=count($data);
    //     $this->assign('news_list',$data);
    //     $this->assign('news_number',$news_number);
    // }


    private function jiangjin($userid)
    {
        // $userid = session('userid');
        $map['id'] = $userid;
        $map['status'] = 1;//0为未激活 1为已激活
        // $map['level'] = 1;//1为代理
        $map['level'] = array('gt',1);//为代理

        $daili_user=M('account')->where($map)->find();

        if(empty($daili_user)){

            return;

        }

        $dailitim=$daili_user['daitime'];
        $dailiday=$daili_user['days2'];

        if(date('Y-m-d', $dailitim)!=date('Y-m-d', time())) {
            $day1 = date('Y-m-d', $dailitim + 24 * 60 * 60);
            $day2 = date('Y-m-d', time());
            $diff = $this->diffBetweenTwoDays($day1, $day2);
            $diff = $diff - $dailiday;
            for ($i = 0; $i <= $diff; $i++) {

                //设置十二点返现
                $createtime = $dailitim + ($dailiday + $i) * 24 * 60 * 60;
                $createtime = date('Y-m-d', $createtime + 24 * 60 * 60);
                $createtime = strtotime($createtime);

                $this->guanli($userid,$createtime);

                //增加返现天数
                $arr = array(
                    'days2' => array('exp', 'days2+1'),
                );
        
                M('account')->where('id='.$userid)->save($arr);

            }
        }

    }

    //管理奖
    private function guanli($userid,$createtime)
    {
        $map['id'] = $userid;
        $map['status'] = 1;//0为未激活 1为已激活
        // $map['level'] = 1;//1为代理
        $map['level'] = array('gt',1);

        $daili=M('account')->where($map)->find();      

        if(empty($daili)){

            return;

        }

        $z_par = M('account')->where(array('parid' => $daili['id'],'status' => 1))->select();
        $z_parnum = count($z_par);

        if($z_parnum==0){
                
            return;

        }

        $sqlw='1=1 and status=1 and';

        for($i=0;$i<$z_parnum;$i++)
        {
            if($i==0){
                $sqlw.=' (';
            }
            $id1 = $z_par[$i]['id'];
            $sqlw.=' parid='.$id1;
            if($i<$z_parnum-1){
                $sqlw.=' or ';
            }else{
                $sqlw.=') ';
            }

        }
        
        // if($daili['investmoney']<5000){
        if($daili['level']==2){

            if($z_parnum>1){

                if($z_parnum>9){

                    $daishu=9;

                }else{
                    $daishu=$z_parnum;
                }

            }else{

                return;

            }


        // }elseif($daili['investmoney']>=5000 && $daili['investmoney']<10000){
        }elseif($daili['level']==3){
    
            if($z_parnum>3 && $z_parnum<=9){

                $daishu=$z_parnum;

            }
            if($z_parnum>9){
                
                $daishu=9;

            }
            if($z_parnum<=3){
                
                $daishu=3;

            }


        // }elseif($daili['investmoney']>=10000 && $daili['investmoney']<20000){
        }elseif($daili['level']==4){
            
            if($z_parnum>5 && $z_parnum<=9){

                $daishu=$z_parnum;

            }
            if($z_parnum>9){
                
                $daishu=9;

            }
            if($z_parnum<=5){
                
                $daishu=5;

            }
            

        // }elseif($daili['investmoney']>=20000 && $daili['investmoney']<30000){
        }elseif($daili['level']==5){
            
            $daishu=9;

        }
        // elseif($daili['investmoney']>=30000){
            
        //     $daishu=9;

        // }

        $setting=M('setting')->where('id=1')->find();

        for($a=1;$a<$daishu;$a++)
        {
            if($a==1 || $a==2){
                $bfb=0.09;
            }
            if($a==3 || $a==4){
                 $bfb=0.07;
            }
            if($a==5 || $a==6){
                $bfb=0.05;
            }
            if($a==7 || $a==8){
                $bfb=0.03;
            }
            // $z_bfb=$bfb * 0.008;
            $z_bfb=$bfb * $setting['rate']/100;

            $sqlw=$this->next_user($sqlw,$a,$z_bfb,$createtime,$userid);
            if(empty($sqlw)){
                 break;
            }

        }

    }
    
    //下一代
    private function next_user($sqlw,$a,$z_bfb,$createtime,$userid)
    {
        $dainum=$a+1;
        $z_par=M('account')->where($sqlw)->select();
        $sqlw2='1=1 and status=1 and';
        $z_parnum = count($z_par);
        
        if($z_parnum==0){

            return;

        }

        for($j=0;$j<$z_parnum;$j++){

            $price = $z_par[$j]['investmoney']*$z_bfb;
            $title='第'.$dainum.'代会员'.$z_par[$j]['account'].'的管理奖';

            $this->doincomefrom($userid,$title,$price,$createtime,3);//每天生成管理奖记录

            if($j==0){
                $sqlw2.=' (';
            }

            $id1 = $z_par[$j]['id'];
            $sqlw2.=' parid='.$id1;
            if($j<$z_parnum-1){
                $sqlw2.=' or ';
            }else{
                $sqlw2.=') ';
            }

        }

        return $sqlw2;
    }

    //每天返现收益
    private function backcash($userid)
    {
        // $userid = session('userid');
        $map['id'] = $userid;
        $map['status'] = 1;

        $jh_user=M('account')->where($map)->find();
        $setting=M('setting')->where('id=1')->find();

        if(date('Y-m-d', $jh_user['jhtime'])!=date('Y-m-d', time())) {
            $day1 = date('Y-m-d', $jh_user['jhtime'] + 24 * 60 * 60);
            $day2 = date('Y-m-d', time());
            $diff = $this->diffBetweenTwoDays($day1, $day2);
            $diff = $diff - $jh_user['days'];
            $title = '投资额日分红';
            for ($i = 0; $i <= $diff; $i++) {
                // $price = $jh_user['investmoney'] * 0.008;//每天返现
                if($jh_user['investmoney']!=0){

                    $price = $jh_user['investmoney'] * $setting['rate']/100;//每天返现

                }
                
                // $price1 = $price * 0.5;//每天返现50%进提现钱包
                // $price2 = $price * 0.2;//每天返现20%进季度钱包
                // $price3 = $price * 0.3;//每天返现30%进半年钱包
                //1写入收益

                //设置十二点返现
                $createtime = $jh_user['jhtime'] + ($jh_user['days'] + $i) * 24 * 60 * 60;
                $createtime = date('Y-m-d', $createtime + 24 * 60 * 60);
                $createtime = strtotime($createtime);

                if($price){

                    $this->doincomefrom($userid, $title, $price, $createtime, 1);//每天返现记录

                }

                //2减去返现
                $arr = array(
                    'days' => array('exp', 'days+1'),
                    // 'cashmoney' => array('exp', 'cashmoney+' . $price1),
                    // 'halfmoney' => array('exp', 'halfmoney+' . $price2),
                    // 'yearmoney' => array('exp', 'yearmoney+' . $price3),
                );
                
                M('account')->where($map)->save($arr);

            }
        }
        
    }

    private function doincomefrom($userid,$title,$price,$createtime,$status)
    {
        $D=M('reward');
        $arr=array(
            'uid'=>$userid,
            'title'=>$title,
            'money'=>$price,
            'times_c'=>$createtime,
            'typemoney'=>$status,
        );
        $D->add($arr);

        $price1 = $price * 0.5;//每天返现50%进提现钱包
        $price2 = $price * 0.2;//每天返现20%进季度钱包
        $price3 = $price * 0.3;//每天返现30%进半年钱包

        $arr2 = array(
            'cashmoney' => array('exp', 'cashmoney+' . $price1),
            'halfmoney' => array('exp', 'halfmoney+' . $price2),
            'yearmoney' => array('exp', 'yearmoney+' . $price3),
        );
        
        M('account')->where('id='.$userid)->save($arr2);

    }

    /**
     * 求两个日期之间相差的天数
     * (针对1970年1月1日之后，求之前可以采用泰勒公式)
     * @param string $day1
     * @param string $day2
     * @return number
     */
    private function diffBetweenTwoDays ($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }

   


 

}
?>